import re
import os.path
import cppAnalyze

class HtmlOutputPlugin(cppAnalyze.Plugin):
    def __init__(self):
        cppAnalyze.Plugin.__init__(self)
        self.pluginName = 'HtmlOutputPlugin'
        self.pluginDescription = 'Formats the output from a collection of plugins as HTML.'

    def getConfigSettings(self):
        return ('dstDir,string','htmlTemplate,string')

    def processPluginOptions(self, argv):
        if not argv:
            print 'Invalid plugin options. Expecting --inputFile <path>.'
            return False

        if '--inputFile' in argv:
            inFileIndex = argv.index('--inputFile') + 1

        if inFileIndex >= len(argv):
            print 'Error: No inputFile was specified.'
            return False
        else:
            self.inputFile = argv[inFileIndex]
            return True

        return False

    def makeStuffGoNow(self):
        htmlTemplate = self.getSetting('htmlTemplate').toString()

        if not htmlTemplate:
            print 'Error: No htmlTemplate was specified in the config-file.'
            return -1
        
        dstDir = self.getSetting('dstDir').toString()

        if not dstDir:
            print 'Error: No dstDir was specified in the config-file.'
            return -1

        try:
            htmlTemplateFile = open(htmlTemplate, 'r')
        except IOError:
            print 'Error: Invalid htmlTemplate.'
            return -1
        
        try:
            inputFile = open(self.inputFile, 'r')
        except IOError:
            print 'Invalid inputFile.'
            return -1

        htmlTemplateOutput = HtmlOutputTemplate(htmlTemplateFile)
        htmlTemplateResult = htmlTemplateOutput.getTemplateByName('Result')

        for inputFileLine in inputFile:
            inputFields = inputFileLine.split('|')
            
            if htmlTemplateResult:
                if len(inputFields) >= 3:
                    htmlLine = htmlTemplateResult.replace('%PLUGIN%', inputFields[0])
                    htmlLine = htmlLine.replace('%FILENAME%', inputFields[1])
                    htmlLine = htmlLine.replace('%LINE%', inputFields[2])
                    htmlTemplateOutput.addToOutput('Result', htmlLine)

        htmlTemplateOutput.saveToFile(dstDir + os.path.sep + 'HtmlOutput.html')

        htmlTemplateFile.close()
        inputFile.close()

        print 'Output Complete: %s.' % (dstDir + os.path.sep + 'HtmlOutput.html')
        return 0

class HtmlOutputTemplate:
    reTemplate = re.compile(r'<!-- Template: (.+) -->')
    rePlaceholder = re.compile(r'<!-- Placeholder: (.+) -->')

    def __init__(self, htmlTemplateFile):       
        self.htmlTemplateFile = htmlTemplateFile
        self.htmlTemplates = dict()
        self.placeholders = list()
        self.placeholderOutput = dict()
        self.loadTemplate()

    def loadTemplate(self):
        self.htmlOutput = list()
        
        isTemplate = False
        templateName = ''
        templateHtml = ''
        
        for htmlTemplateLine in self.htmlTemplateFile:
            if isTemplate:
                if htmlTemplateLine.strip() == '<!--':
                    continue
                
                if htmlTemplateLine.strip() == '-->':
                    isTemplate = False
                    self.htmlTemplates[templateName] = templateHtml
                    templateName = ''
                    templateHtml = ''
                    continue

                templateHtml += htmlTemplateLine
                continue

            reMatch = re.match(HtmlOutputTemplate.reTemplate, htmlTemplateLine.strip())

            if reMatch:
                isTemplate = True
                templateName = reMatch.group(1)
                continue

            reMatch = re.match(HtmlOutputTemplate.rePlaceholder, htmlTemplateLine.strip())

            if reMatch:
                self.placeholders.append(reMatch.group(1))

            self.htmlOutput.append(htmlTemplateLine)

    def getTemplateByName(self, templateName):
        if templateName in self.htmlTemplates:
            return self.htmlTemplates[templateName]

        return None

    def addToOutput(self, placeholder, htmlOutput):
        outputList = None
        
        if placeholder in self.placeholderOutput:
            outputList = self.placeholderOutput[placeholder]
        else:
            outputList = list()
            self.placeholderOutput[placeholder] = outputList

        outputList.append(htmlOutput)

    def saveToFile(self, outputFile):
        try:
            outFile = open(outputFile, 'w')
        except IOError:
            print 'Unable to open outputFile.'
            return False

        for htmlOutputLine in self.htmlOutput:
            reMatch = re.match(HtmlOutputTemplate.rePlaceholder, htmlOutputLine.strip())

            if reMatch:
                if reMatch.group(1) in self.placeholderOutput:
                    placeholderHtmlList = self.placeholderOutput[reMatch.group(1)]
                    htmlOutputLine = htmlOutputLine.replace(reMatch.group(0), '\n'.join(placeholderHtmlList))

            outFile.write(htmlOutputLine)

        outFile.close()

        return True

if __name__ == '__main__':
        exit(HtmlOutputPlugin().runPlugin())
